<script lang="ts">
	import type { CardInfo } from '$lib/api/proto/resource_card_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';

	const PAGE_SIZE = 10;

	interface Props {
		resourceId: string;
		cardInfo: CardInfo;
		onCancel: () => void;
		onOk: () => void;
	}

	const props: Props = $props();

	let linkCardIdList = $state((props.cardInfo.linkList ?? []).map((item) => item.cardId));

	let cardList = $state([] as CardInfo[]);
	let totalCount = $state(0);
	let curPage = $state(0);

	const pageCount = $derived(Math.ceil((totalCount ?? 0) / PAGE_SIZE));

	async function loadCardList() {
		if (userStore.userSession == null) {
			return;
		}
		const res = await callApi(
			appStore.resourceCardApiClient.list({
				sessionId: userStore.userSession,
				resourceId: props.resourceId,
				withContent: false,
				offset: PAGE_SIZE * curPage,
				limit: PAGE_SIZE,
				filterByKeyword: false,
				keyword: ''
			}).response
		);
		totalCount = res.totalCount;
		cardList = res.cardList;
	}

	async function runLink(cardId: string) {
		if (cardId == props.cardInfo.cardId || userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.resourceCardApiClient.link({
				sessionId: userStore.userSession,
				resourceId: props.resourceId,
				cardId1: props.cardInfo.cardId,
				cardId2: cardId
			}).response
		);
	}

	async function runUnLink(cardId: string) {
		if (cardId == props.cardInfo.cardId || userStore.userSession == null) {
			return;
		}
		await callApi(
			appStore.resourceCardApiClient.unlink({
				sessionId: userStore.userSession,
				resourceId: props.resourceId,
				cardId1: props.cardInfo.cardId,
				cardId2: cardId
			}).response
		);
	}

	async function adjustLink() {
		for (const link of props.cardInfo.linkList) {
			if (!linkCardIdList.includes(link.cardId)) {
				await runUnLink(link.cardId);
			}
		}
		const oldLinkCardIdList = props.cardInfo.linkList.map((item) => item.cardId);
		for (const cardId of linkCardIdList) {
			if (!oldLinkCardIdList.includes(cardId)) {
				await runLink(cardId);
			}
		}
		props.onOk();
	}

	$effect(() => {
		loadCardList();
	});
</script>

<dialog class="modal modal-open">
	<div class="modal-box flex-col space-y-4">
		<h3 class="text-lg font-bold">设置相关知识卡片</h3>
		<div class="max-h-[60vh] overflow-y-auto space-y-4">
			{#each cardList as card}
				<div class="flex overflow-hidden truncate gap-2">
					<input
						type="checkbox"
						checked={linkCardIdList.includes(card.cardId)}
						class="checkbox"
						disabled={card.cardId == props.cardInfo.cardId}
						onchange={(e) => {
							if (e.currentTarget.checked) {
								linkCardIdList.push(card.cardId);
							} else {
								linkCardIdList = linkCardIdList.filter((item) => item != card.cardId);
							}
						}}
					/>
					{card.basicInfo?.title}
				</div>
			{/each}
		</div>
		{#if pageCount > 1}
			<div class="join bg-base-200 absolute right-[20px]">
				{#if curPage != 0}
					<button
						class="join-item btn btn-sm {curPage == 0 ? 'btn-active' : ''}"
						onclick={() => (curPage = 0)}>1</button
					>
				{/if}
				{#if pageCount > 3 && curPage > 1}
					<button class="join-item btn btn-sm btn-disabled">...</button>
				{/if}
				{#if curPage < pageCount}
					<button class="join-item btn btn-sm btn-active">{curPage + 1}</button>
				{/if}
				{#if curPage + 1 < pageCount}
					<button class="join-item btn btn-sm" onclick={() => (curPage += 1)}>{curPage + 2}</button>
				{/if}
				{#if pageCount - curPage > 4}
					<button class="join-item btn btn-sm btn-disabled">...</button>
				{/if}
				{#if pageCount - curPage > 3}
					<button class="join-item btn btn-sm" onclick={() => (curPage = pageCount - 2)}
						>{pageCount - 1}</button
					>
				{/if}
				{#if pageCount - curPage > 2}
					<button class="join-item btn btn-sm" onclick={() => (curPage = pageCount - 1)}
						>{pageCount}</button
					>
				{/if}
			</div>
		{/if}
		<div class="modal-action mt-[60px]">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button class="btn btn-primary" onclick={() => adjustLink()}>设置</button>
		</div>
	</div>
	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>
